#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# ***************************************************************************
# 本脚本调用为知笔记的接口，发送markdown文件到为知笔记
# 为知笔记接口:
#   https://www.wiz.cn/wapp/pages/book/bb8f0f10-48ca-11ea-b27a-ef51fb9d4bb4/475c9ef0-4e1a-11ea-8f5c-a7618da01da2
# deepin: 
#   sudo apt install python3-pip
#   sudo pip3 install requests
# 已知问题
# 1. 文件路由有空格时，无法识别正确的文件名
# 2. xml文件读取有误,xml行读取不出来,可能是接口问题
# ***************************************************************************

import sys
import requests
import json
import base64
#from requests_toolbelt.multipart.encoder import MultipartEncoder

WIZNOTE_AS_URL = 'http://as.wiz.cn'
WIZNOTE_LOGIN_URL = WIZNOTE_AS_URL + '/as/user/login'
WIZNOTE_LOGOUT_URL = WIZNOTE_AS_URL + '/as/user/logout'
EMPTY_NOTE = "<html><head></head><body></body></html>"
WIZNOTE_USER_INFO = {
    'userId':"18762673155@163.com",
    'password' :"#Liwl@1991!M",
    'category':"/上传暂存/"
}

class WizNoteAPI():

    def __init__(self,config_json):
        """
         一次请求,初始化存储必要的信息
        """
        self.__config_json = config_json
        #self.__user,self.__password,self.__default_category = self.__read_userid_password()
        self.__user,self.__password,self.__default_category = self.__get_userid_password()
        self.__user_info = self.__login()
        self.__token = self.__user_info.get('token')
        self.__kb_server = self.__user_info.get('kbServer')
        self.__kb_guid = self.__user_info.get('kbGuid')
        self.__header = {"X-Wiz-Token":self.__token}

    def __del__(self):
        self.__logout()

    def __get_userid_password(self):
        """
        从脚本自身读取
        """
        return WIZNOTE_USER_INFO.get('userId'),WIZNOTE_USER_INFO.get('password'),WIZNOTE_USER_INFO.get('category')

    def __read_userid_password(self):
        """
        从配置文件读取帐号密码
        """
        try:
            with open(self.__config_json,'r') as f:
                data = json.load(f)
                user = data.get('userId')
                password = data.get('password')
                default_category = data.get('category')
                if not all([user,password,default_category]):
                    print("配置文件未(正确)指定userId或password")
                    sys.exit(0)
        except IOError:
            print("未(正确)指定配置文件")
            sys.exit(0)
        return (user,password,default_category)

    def __login(self):
        user_data = {
            'userId': self.__user,
            'password': self.__password
        }
        requests_rtn = requests.post(url = WIZNOTE_LOGIN_URL, data = user_data)
        rtn_json = requests_rtn.json()
        if rtn_json.get('return_code') != 200:
            print("帐号密码错误")
            sys.exit(0)
        else:
            return requests_rtn.json().get('result')

    def __logout(self):
        """
        注销token
        """
        return requests.get(url=WIZNOTE_LOGOUT_URL)

    def __exec_request(self,method,url,body,files=None):
        """
        封装请求
        """
        self.__header.update({"Content-Type":"application/json"})
        if method == 'post':
            #插入信息
            request_rtn = requests.post(url=url,headers=self.__header,data=body,files=files)
        if method == 'get':
            #获取信息
            request_rtn = requests.get(url=url,headers=self.__header,data=body,files=files)
        if method == 'put':
            #更新信息
            request_rtn = requests.put(url=url,headers=self.__header,data=body,files=files)
        if method == 'delete':
            #删除信息
            request_rtn = requests.delete(url=url,headers=self.__header)
        return request_rtn

    def create_note(self,notefile):
        """
        创建笔记,返回的是笔记的信息{"title":"docGuid"},包括docGuid
        """
        content = "</br>"
        title_guid = {}
        request_url = self.__kb_server + '/ks/note/create/' + self.__kb_guid

        #根据路径获取文章标题
        title = notefile.split("/")[-1]

        with open(notefile,'r') as html:
            lines = html.readlines()
            for line in lines:
                content = content +  '</br>' + line

        request_data = {
            'kbGuid': self.__kb_guid,
            'category': self.__default_category,
            'title': title,
            'html': content
        }

        request_rtn = self.__exec_request(method='post',url=request_url,body=json.dumps(request_data))
        title_guid.update({title:request_rtn.json().get('result').get('docGuid')})
        return title_guid


    def get_notes_title_guid(self,start=0,count=100):
        """
        获取某个文件夹下的笔记的title,guid
        """
        title_docguid = {}
        request_url = \
             self.__kb_server + '/ks/note/list/category/' + self.__kb_guid + \
             '?category=%s&withAbstract=false&start=%s&count=%s&orderBy=created&ascending=asc' \
             % (self.__default_category,start,count)
        request_rtn = self.__exec_request(method='get',url=request_url,body=None)
        for note in request_rtn.json().get('result'):
            title_docguid.update({note.get('title'):note.get('docGuid')})
        return title_docguid


    def has_note(self,title):
        """
        判断笔记是否存在。有返回guid,无返回None
        """
        return self.get_notes_title_guid().get(title)

    def delete_note(self,title):
        """
        删除笔记
        """
        note_guid = self.has_note(title)
        request_url = self.__kb_server + '/ks/note/delete/' + self.__kb_guid + '/' + note_guid
        request_rtn = self.__exec_request(method='delete',url=request_url,body="")
        return request_rtn
        

    def update_note(self,title):
        """
        更新笔记。这样的笔记没有历史记录。
        """
        self.delete_note(title)
        self.create_note(title)


    def upload_images(self,title,image_file):
        """
        上传图片,需要先创建一个空笔记
        """
        self.__header.update({'Content-Type':'multipart/form-data'})

        def image_to_str(image):
            with open(image,'rb') as f:
                image_byte=base64.b64encode(f.read())
            return image_byte.decode('utf-8')

        note_guid = self.has_note(title)
        if not note_guid:
            note_guid = self.create_note(title,html=None)

        request_url = self.__kb_server + '/ks/resource/upload/' + self.__kb_guid +'/'+ note_guid
        print(request_url)

        image = {
            'data': ('dog',open(image_file,'rb'),'image/jpeg')
        }
        print(image)

        data = {
            'kbGuid': self.__kb_guid,
            'docGuid': note_guid
        }
        print(data)
        request_file = {
            'kbGuid': (None,self.__kb_guid),
            'docGuid': (None,note_guid),
            'data': (('dog',open(image_file,'rb')),'image/jpeg')
        }

        #request_rtn = self.__exec_request(method='post',url=request_url,body=data,files=image)
        request_rtn = self.__exec_request(method='post',url=request_url,body=None,files=request_file)
        print(request_rtn.text)

if __name__ == "__main__":
    my_wiznote = WizNoteAPI('config.json')
    if len(sys.argv) != 3:
        sys.exit(0)
    if sys.argv[1]  == "--file":
        notefile = sys.argv[2]
        note_guid = my_wiznote.has_note(notefile)
        if note_guid:
            my_wiznote.update_note(notefile)
        else:
            my_wiznote.create_note(notefile)
